package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.dto.RoleDTO;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.TimeUtil;
import com.ruoyi.system.constants.DyRoleKeyConstants;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.IDyCommonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.DyRemitRecordBo;
import com.ruoyi.system.domain.vo.DyRemitRecordVo;
import com.ruoyi.system.domain.DyRemitRecord;
import com.ruoyi.system.mapper.DyRemitRecordMapper;
import com.ruoyi.system.service.IDyRemitRecordService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 打款记录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-06-20
 */
@RequiredArgsConstructor
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class DyRemitRecordServiceImpl implements IDyRemitRecordService {

    private final DyRemitRecordMapper baseMapper;
    private final SysDeptMapper sysDeptMapper;

    @Resource
    IDyCommonService iDyCommonService;

    /**
     * 查询打款记录
     */
    @Override
    public DyRemitRecordVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询打款记录列表
     */
    @Override
    public TableDataInfo<DyRemitRecordVo> queryPageList(DyRemitRecordBo bo, PageQuery pageQuery, LoginUser loginUser) {
        RoleDTO roleDTO = iDyCommonService.getFirstRole(loginUser.getRoles());
        if (ObjectUtil.isEmpty(roleDTO)){
            throw new ServiceException("无数据查看权限");
        }

        LambdaQueryWrapper<DyRemitRecord> lqw = buildQueryWrapper(bo);

        if (roleDTO.getRoleKey().equals(DyRoleKeyConstants.roleKeySubCompany)){
            lqw.eq(DyRemitRecord::getCompanyId,loginUser.getDeptId());
        }

        if (ObjectUtil.isNotEmpty(bo.getStartDate()) && ObjectUtil.isNotEmpty(bo.getEndDate())){
            Date startTimeStart = TimeUtil.strToDateStart(bo.getStartDate());
            Date startTimeEnd = TimeUtil.strToDateStart(bo.getEndDate());
            log.info("DyRemitRecordServiceImpl,queryPageList,startTimeStart:{}",startTimeStart);
            log.info("DyRemitRecordServiceImpl,queryPageList,startTimeEnd:{}",startTimeEnd);
            if (ObjectUtil.isNotEmpty(startTimeStart) && ObjectUtil.isNotEmpty(startTimeEnd)){
                lqw.between(DyRemitRecord::getCreateTime,startTimeEnd ,startTimeStart);
            }
        }

        lqw.orderByDesc(DyRemitRecord::getUpdateTime);
        Page<DyRemitRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollectionUtil.isNotEmpty(result.getRecords())){
            buildDyRemitRecordVo(result.getRecords());
        }
        return TableDataInfo.build(result);
    }

    private void buildDyRemitRecordVo(List<DyRemitRecordVo> list){
        List<Long> companyIdList = list.stream().map(DyRemitRecordVo::getCompanyId).collect(Collectors.toList());
        LambdaQueryWrapper<SysDept> deptLambdaQueryWrapper = new LambdaQueryWrapper<>();
        deptLambdaQueryWrapper.in(SysDept::getDeptId,companyIdList);
        List<SysDept> deptList = sysDeptMapper.selectDeptList(deptLambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(deptList)){
            Map<Long,SysDept> deptMap = deptList.stream().collect(Collectors.toMap(SysDept::getDeptId,item -> item,(k1,k2) -> k1));
            for (DyRemitRecordVo item : list){
                if (ObjectUtil.isNotEmpty(deptMap) && ObjectUtil.isNotEmpty(deptMap.get(item.getCompanyId()))){
                    item.setCompanyName(deptMap.get(item.getCompanyId()).getDeptName());
                }
            }
        }
    }

    /**
     * 查询打款记录列表
     */
    @Override
    public List<DyRemitRecordVo> queryList(DyRemitRecordBo bo) {
        LambdaQueryWrapper<DyRemitRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DyRemitRecord> buildQueryWrapper(DyRemitRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DyRemitRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCompanyId() != null, DyRemitRecord::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getAmount() != null, DyRemitRecord::getAmount, bo.getAmount());
        return lqw;
    }

    /**
     * 新增打款记录
     */
    @Override
    public Boolean insertByBo(DyRemitRecordBo bo) {
        DyRemitRecord add = BeanUtil.toBean(bo, DyRemitRecord.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改打款记录
     */
    @Override
    public Boolean updateByBo(DyRemitRecordBo bo) {
        DyRemitRecord update = BeanUtil.toBean(bo, DyRemitRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DyRemitRecord entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除打款记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
